package awk.serializer;

import java.nio.ByteBuffer;

public class Serialized {

	public static void main(String[] args) {
		Serialized serialized = new Serialized("码农小麦",25);
		System.out.println(serialized);
		byte[] bytes = serialized.toByte();
		Serialized sb = serialized.fromByte(bytes);
		System.out.println(sb);
	}


	private String name;
	private int age;

	public Serialized(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Bird{" + "name='" + name + '\'' + ", age=" + age + '}';
	}

	public byte[] toByte() {
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		byte[] names = this.name.getBytes();
		//1
		byteBuffer.putInt(names.length);
		//2
		byteBuffer.put(names);
		//3
		byteBuffer.putInt(age);
		return byteBuffer.array();
	}

	public Serialized fromByte(byte[] bytes) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
		byteBuffer.put(bytes);
		byteBuffer.flip();
		//1
		int length = byteBuffer.getInt();
		byte[] tmpbytes = new byte[length];
		//2
		byteBuffer.get(tmpbytes);
		String name = new String(tmpbytes);
		//3
		int age = byteBuffer.getInt();
		return new Serialized(name, age);
	}
}
